<?php
/**
* session mysql处理类
* session各方法调用顺序：
* __construct -> open -> read ->write -> close
*/
class SessionMysql extends AbsSessionHandle {	
	public function __construct($cfg) {
		parent::__construct($cfg);
	}
	
	public function open($savepath, $name) {
		return TRUE;
	}
	
	public function close() {
		return TRUE;
	}
	
	public function read($id) {
		$db = wl_get_db();
		$sql = "SELECT value FROM " . TABLE_SESSION . " WHERE sesskey = '{$id}' AND expiry > '" . time() . "'";
		$session = $db->sql_select_array($sql, MYSQL_ASSOC);
		return $session ? base64_decode($session[0]['value']) : '';
	}
	
	public function write($id, $sess_data) {
		$db = wl_get_db();
		$sess_data = $db->sql_escape(base64_encode($sess_data));
		$expiry = time() + $this->lifetime;
		$sql = "SELECT value FROM " . TABLE_SESSION . " WHERE sesskey = '{$id}'";
		$session = $db->sql_select_array($sql, MYSQL_ASSOC);
		if($session) {
			$sql = "UPDATE " . TABLE_SESSION . " SET value = '{$sess_data}', expiry = '" . $expiry . "' WHERE sesskey = '{$id}'";
		} else {
			$sql = "INSERT INTO " . TABLE_SESSION . " (sesskey, expiry, value) VALUES ('{$id}', '" . $expiry . "', '{$sess_data}')";
		}
		return $db->sql_execute($sql);
	}
	
	public function destroy($id) {
		$db = wl_get_db();
		$sql = "DELETE FROM " . TABLE_SESSION . " WHERE sesskey = '{$id}'";
		return $db->sql_delete($sql);
	}
	
	public function gc($maxlifetime) {
		$db = wl_get_db();
		$sql = "DELETE FROM " . TABLE_SESSION . " WHERE expiry  < '" . time() . "'";
		return $db->sql_delete($sql);
	}
}
?>